out vec4 FragColor;

#include "Math.glh"


#ifdef CUBEMAP2CUBEMAP

in vec3 fragUv;
uniform samplerCube skybox;

vec4 sampleEnv(vec3 cubeuv){
    return texture(skybox,cubeuv);
}

void main()
{    
    vec3 normal = normalize(fragUv);
    vec3 irrandiance = vec3(0.0);
    vec3 up    = vec3(0.0, 1.0, 0.0);
    vec3 right = cross(up, normal);
    up         = cross(normal, right);

    float sampleDelta = 0.025;
    float nrSamples = 0.0; 
    for(float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta)
    {
        for(float theta = 0.0; theta < 0.5 * PI; theta += sampleDelta)
        {
            // spherical to cartesian (in tangent space)
            vec3 tangentSample = vec3(sin(theta) * cos(phi),  sin(theta) * sin(phi), cos(theta));
            // tangent space to world
            vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * N; 

            irradiance += sampleEnv(sampleVec).rgb * cos(theta) * sin(theta);
            nrSamples++;
        }
    }
    irradiance = PI * irradiance * (1.0 / float(nrSamples));
    FragColor = vec4(irradiance,1.0);
}



#endif

#ifdef CUBEMAP2SPHERICALMAP

#endif

#ifdef SPHERICALMAP2CUBEMAP

#endif

#ifdef SPHERICALMAP2SPHERICALMAP

const vec2 invAtan = vec2(0.1591,0.3183);
vec2 sampleSphericalMap(vec3 v){
    vec2 uv = vec2(atan(v.z,v.x),asin(v.y));
    uv *= invAtan;
    uv += 0.5;
    return uv;
}

vec3 toCubeUv(vec2 uv){
    uv -= 0.5;
    uv /= invAtan;
    vec3 cubeuv;
    cubeuv.y = sin(uv.y);
    float rate = tan(uv.x);
    cubeuv.x = 1 / rate - 1;
    cubeuv.z = 1 - rate;
    return cubeuv;
}

uniform sampler2D skybox;


vec4 sampleEnv(vec3 cubeuv){
    vec2 uv = sampleSphericalMap(normalize(cubeuv));
    return texture(skybox, uv);
}

in vec2 uv;
void main()
{    
    vec3 fragUv = toCubeUv(uv);
    vec3 normal = normalize(fragUv);


    vec3 irrandiance = vec3(0.0);
    vec3 up    = vec3(0.0, 1.0, 0.0);
    vec3 right = cross(up, normal);
    up         = cross(normal, right);

    float sampleDelta = 0.025;
    float nrSamples = 0.0; 
    for(float phi = 0.0; phi < 2.0 * PI; phi += sampleDelta)
    {
        for(float theta = 0.0; theta < 0.5 * PI; theta += sampleDelta)
        {
            // spherical to cartesian (in tangent space)
            vec3 tangentSample = vec3(sin(theta) * cos(phi),  sin(theta) * sin(phi), cos(theta));
            // tangent space to world
            vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * N; 

            irradiance += sampleEnv(sampleVec).rgb * cos(theta) * sin(theta);
            nrSamples++;
        }
    }
    irradiance = PI * irradiance * (1.0 / float(nrSamples));
    FragColor = vec4(irradiance,1.0);
}

#endif




